import json
import os
from collections import OrderedDict
from oa_system.utils.permissions import IsOwnerOrReadOnly
import django_filters
from django.conf import settings
from django.http import FileResponse
from openpyxl import load_workbook
from django_filters import rest_framework as filters
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
import urllib.parse

from oa_system.utils.CustomPagination import CustomPagination
# from students.models import Class, Student
from students.serializers import ClassSerializer,StudentSerializer
from teacherclass.models import RollCall
from system.models import Department
# from oa_system.api.system.models import *
# from oa_system.api.teacherclass.models import *
from .models import *
class ClassView(ModelViewSet):
    queryset = Class.objects.all()#查询集
    serializer_class = ClassSerializer #序列化器
    pagination_class = CustomPagination
    def list(self, request, *args, **kwargs):
        college_id=request.query_params.get('college_id')
        queryset=request.query_params.get('queryset')
        if queryset=='nopaged':
            self.pagination_class = None
        if(college_id):
            self.queryset=Class.objects.filter(school_id=college_id)
        return super(ClassView, self).list(request)
    def getIsGaoZhi(self,request):
        class_id=request.query_params.get("class_id")
        depid=Class.objects.filter(id=class_id).values("school_id")[0]["school_id"]
        is_gaozhi=Department.objects.filter(id=depid).values("is_gaozhi")[0]["is_gaozhi"]
        print(is_gaozhi)
        return Response(is_gaozhi)
    def getClassInfo(self,request):
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 5))
        if page_size > 20:
            page_size = 20
        college_id = request.query_params.get('college_id')
        queryset = request.query_params.get('queryset')
        result=[]
        if (college_id):
            for i in Class.objects.filter(school=college_id).values():
                dict_ = {}
                dict_['id'] = i['id']
                dict_['name'] = i['name']
                dict_['school'] = list(Department.objects.filter(id=i['school_id']).values())[0]
                dict_['student_num'] = len(Student.objects.filter(cls=i['id']))
                result.append(dict_)
        else:
            for i in  Class.objects.all().values():
                dict_={}
                dict_['id']=i['id']
                dict_['name']=i['name']
                dict_['school']=list(Department.objects.filter(id=i['school_id']).values())[0]
                dict_['student_num']=len(Student.objects.filter(cls=i['id']))
                result.append(dict_)
        if queryset== 'nopaged':
            return Response(result)
        start = (page - 1) * page_size
        data = {'count': len(result), 'data': list(result[start:page * page_size])}
        return Response(data)

class StudentFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='contains')
    market = django_filters.CharFilter(lookup_expr='contains')
    dormnumber = django_filters.CharFilter(lookup_expr='contains')
    class Meta:
        model = Student
        fields = ['sex', 'cls']
def download_excel_temp(request):
    response = FileResponse(
        open(settings.EXCEL_FIEL_PATH + '/振涛教育学生信息统计模板.xlsx', 'rb'))
    #用户点击下载链接之后 下载的文件的 文件名
    file_name='振涛教育-学生信息统计模板.xlsx'
    #告诉浏览器响应内容的类型为 二进制文件
    response['Content-Type'] = 'application/octet-stream'

    file_name = 'attachment; filename=%s' % file_name
    response['Content-Disposition'] = file_name.encode('utf-8', 'ISO-8859-1')
    return response
class StudentView(ModelViewSet):
    queryset = Student.objects.all() #查询集
    serializer_class = StudentSerializer #指定序列化器

    # permission_classes = (IsOwnerOrReadOnly,)
    #127.0.0.1:8888/students?name=zhangsan
    #指定使用 django-filter进行过滤查询
    filter_backends = (filters.DjangoFilterBackend,)
    #指定自定义的过滤器
    filterset_class = StudentFilter

    # def list(self, request, *args, **kwargs):
    #     print(request.user)
    #     return super(StudentView, self).list(request, *args, **kwargs)
    @action(methods=['post'],detail=False)
    def uploadexcel(self,request):
        school_id=request.data.get('school')
        class_id=request.data.get('cls')
        file = request.FILES.get('stufile')
        ext = file.name.rsplit('.', maxsplit=1)[1]  # 截取文件的后缀名
        filename = 'school_'+str(school_id)+'_cls_'+str(class_id) + '.' + ext
        filepath = settings.EXCEL_FIEL_PATH + filename

        with open(filepath, 'wb+') as f:
            for chunk in file.chunks():
                f.write(chunk)
        # 定义excel表中 每一列的值与数据表字段的映射关系 例如：excel第一列值对应数据表中的name字段值...
        excel_field = ('name', 'phone', 'idcardnumber', 'sex', 'family_phone', 'relations', 'address', 'dormnumber',
                       'bednumber', 'market')
        wb = load_workbook(filename=filepath)  # 加载excel文件
        ws = wb.active  # 获取excel文件中的第一张表
        student_obj_list = []  # 定义学生对象（已经填充好数据）列表
        excel_rows = list(ws.rows)  # 获取表中的所有行 并转化成列表
        excel_rows.pop(0)  # 排除第一行的文档标题
        classobj=Class.objects.get(pk=class_id)
        idcard_list=[]#文件中所有学生的身份证号
        # 从第二行开始读取 每一列中的值
        for row in excel_rows:
            obj = Student()  # 定义一个空的学生对象
            obj.cls = classobj  # 设置每个学生的班级id
            obj_attr = obj.__dict__  # 以字典的形式获取学生对象的属性信息（字典：{属性名:属性值...}）
            # 遍历数据行中的每一列 column
            for i, column in enumerate(row):
                if i == len(excel_field):
                    break  # 固定列数
                if column.value is None:
                    return Response({'error': '存在为空的单元格！' + str(column)})
                attr_name = excel_field[i]  # 根据列的下标获取对应的数据表字段
                if attr_name=='idcardnumber':
                    idcard_list.append(column.value)
                obj_attr[attr_name] = column.value  # 根据表字段（对应的是StudentInfo模型所产生的对象的属性）对 对象属性进行赋值
            student_obj_list.append(obj)  # 将构造好的学生信息对象 插入到列表中
        exist_students=Student.objects.filter(idcardnumber__in=idcard_list).values()
        if exist_students:
            exist_students_id=','.join([i.get('idcardnumber') for i in exist_students])

            return Response({'error':'已存在身份证号相同学生：'+exist_students_id})

        result = Student.objects.bulk_create(student_obj_list)  # 一次性插入到数据表
        if result:
            os.remove(filepath)
            return Response({'success':'成功'})
        return Response({'error': '导入失败！'})
    #获取学生的点名信息
    def getStudentsRollCall(self,request):
        #获取班级id
        class_id=request.query_params.get('cls_id')
        #获取原课节日期
        class_date=request.query_params.get('class_date')
        #获取课节
        class_section=request.query_params.get('class_section')
        try:
            rc=RollCall.objects.get(class_section=class_section,class_date=class_date)
            data={}
            data['normal']=StudentSerializer(Student.objects.filter(idcardnumber__in=rc.normal.split(',')),many=True).data
            data['cut_classes']=StudentSerializer(Student.objects.filter(idcardnumber__in=rc.cut_classes.split(',')),many=True).data
            data['leave']=StudentSerializer(Student.objects.filter(idcardnumber__in=rc.leave.split(',')),many=True).data
            return Response(data)
        except:
            # 根据班级id 获取所有的学生信息
            students = Student.objects.filter(cls_id=class_id)
            ser=StudentSerializer(students,many=True)
            print(ser.data)
            return Response(ser.data)

    # 根据学院和班级信息
    def College_Class(self,request):
        colleges_id=list(Department.objects.filter(name='学院').values())[0]['id']
        colleges_list=[]
        for i in list(Department.objects.filter(pid_id=colleges_id).values()):
            dict_={}
            dict_['id']=i['id']
            dict_['name']=i['name']
            dict_['children']=list(Class.objects.filter(school_id=i['id']).values())
            colleges_list.append(dict_)
        print(colleges_list)
        data={"data":colleges_list,"status":200,"message":"获取数据成功"}
        return Response(data)
    def getStudentByClass(self,request):
        class_id=request.query_params.get('classId')
        list_=list(Student.objects.filter(cls_id=class_id).values())
        data={ 'data':list_,"status":200,'message':'获取学生信息成功' }
        return Response(data)

    def raiseDropClass(self,request):
        data = json.loads(request.body.decode())
        print(data)
        newClassId=data['newClassId']
        studentsId=data['studentsId']
        for i in studentsId:
            Student.objects.filter(id=i).update(cls_id=newClassId)
        data={
            'status':200,
            'message':'修改班级成功'
        }
        return Response(data)







